#include <stdio.h>
#include <time.h>
#include <windows.h>
#include <stdlib.h>  
#include <string>
#include <vector>

#define _MAX_NUM 1000000
#define _MOD_VAL 1000007
#define _PROB_VAL 42
#define _FILES_DIFFER_VAL -1
#define _FILES_DIFFER_CNT -2

std::vector<int> Y,Z;

void SwapTwo (int &a, int &b){
	int tmp = a;
		a = b;
		b = tmp;
}

void PrintToFile (std::vector<int> &Z, FILE *outFile, char &divider){
	int len = Z.size();
	for (int i = 0; i < len-1; i++)
		fprintf(outFile, "%d%c", Z[i], divider);
	fprintf(outFile, "%d", Z[len-1]);
}

void MixUp(std::vector<int> &Z){
	srand(time(NULL));
	int len = Z.size();
	int el1, el2;
	for (int i = 0; i < len; i++){
		el1 = rand() % len;
		el2 = rand() % len;
		SwapTwo(Z[el1], Z[el2]);
	}
}

int CompareFiles(FILE *outRes, FILE *outStd){
	int tmpRes, tmpStd;

	while ( (fscanf(outRes, "%d", &tmpRes) != EOF)
		&& (fscanf(outStd, "%d", &tmpStd) != EOF) )
			if (tmpRes != tmpStd) return tmpRes;
	if ((fscanf(outRes, "%d", &tmpRes) == EOF)
		&& (fscanf(outStd, "%d", &tmpStd) == EOF))
			return 0;
	else return _FILES_DIFFER_CNT;
}

int main(int argc, char *argv[]){
	int i;
	char *testFile = argv[1];
	char *cmpFile = argv[2];
	char *outFile = argv[3];
	char divider = ',';

	for(int testNum = 1; testNum < 10; testNum ++){
		srand(time(NULL));

		FILE *outTestFile = fopen (testFile, "wt");
		FILE *outCmpFile = fopen (cmpFile, "wt");

		int x = rand() % _PROB_VAL;
		for (int i = 0; i < _MAX_NUM; i += x){
			x = rand() % _PROB_VAL;
			Y.push_back(i);
			Z.push_back(i);
		}

		MixUp(Z);
	
		PrintToFile(Z, outTestFile, divider);
		PrintToFile(Y, outCmpFile, divider);

		fclose(outTestFile);
	
		std::string RunKey = "mapped_sort.exe 1.txt 2.txt 0";
		WinExec(RunKey.c_str(), 1);

		FILE *outProgFile = fopen (outFile, "r");
	
		int resCmp = CompareFiles(outProgFile, outCmpFile);
		
		switch (resCmp){
			case 0: {
				printf("test %d numbers OK\n", Z.size());
				break;
			}
			default: {
				printf("test %d numbers Failed Error %d\nStopped\n", Z.size(), resCmp);
				scanf("%d", i);
			}
		}
		
		fclose(outProgFile);		
		fclose(outTestFile);		
		fclose(outCmpFile);
	}
	printf("tested Successfully\n");
	return 0;
}